package ua.lk.phonebook;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ua.lk.phonebook.dao.UserDao;
import ua.lk.phonebook.model.User;

/**
 * Servlet implementation class CheckLogin
 */
@WebServlet(description = "Авторизация пользователя", urlPatterns = { "/checklogin" })
public class CheckLogin extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CheckLogin() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
  
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		// TODO Auto-generated method stub
		String login = request.getParameter("username");
		String password =  request.getParameter("password");
		String backToUrl = request.getParameter("backto").replace("$", "&");
		
		UserDao dao = new UserDao();
		
		User user = null;
		if( login != null && password != null )			
		{
			user = dao.checkUserPassword(login, password);
			if(user != null)
			{
				HttpSession session = request.getSession(true);
				session.setAttribute("login", login);
				session.setAttribute("username", user.getUsername());
				session.setAttribute("usergroup", user.getRoles_text());				
			}
		}
		if( user == null)
		{
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/html; charset=UTF-8");
			PrintWriter out = response.getWriter(); 
			out.println("<p class=\"login-error\">Помилка! Ім'я або пароль користувача не знайдено!</p>");
			RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
			rd.include(request, response);
			
		}
		else
			 response.sendRedirect(backToUrl.substring(1));
		/*
		{
			System.out.println("backto: "+backToUrl);
			RequestDispatcher rd = request.getRequestDispatcher(backToUrl);
			//System.out.println("users_forward:"+forward);
			rd.forward(request, response);
		}
		*/
		dao.closeConnection();
		//System.out.println("connection closed!");
	}

}
